<template>
    <view>
        <u-navbar :title="titleText" :autoBack="true" :placeholder="true">
        </u-navbar>
        <view class="main">
            <u--form class="form" ref="bookInfo" :model="curInputBook" :rules="rules">
                <u-form-item class="formItem" label="ISBN" prop="ISBN" borderBottom>
                    <u--input disabled v-model="curInputBook.ISBN" border="none"></u--input>
                </u-form-item>
                <!-- 封面 -->
                <u-form-item class="formItem" label="封面" prop="coverImage" borderBottom>
                    <u-upload uploadText="上传封面图片" :fileList="curInputBook.coverImage" :maxCount="1"
                        @afterRead="afterReadCoverImage" @delete="deleteCoverImage" width="6rem" height="8rem">
                    </u-upload>
                    <i style="color:#ff5a5f; font-size: 1.5rem; font-style:normal; margin-left:0.5rem">*</i>
                </u-form-item>
                <u-form-item class="formItem" label="书名" prop="bookTitle" borderBottom>
                    <u--input v-model="curInputBook.bookTitle"></u--input>
                    <i style="color:#ff5a5f; font-size: 1.5rem; font-style:normal; margin-left:0.5rem">*</i>
                </u-form-item>
                <u-form-item class="formItem" label="作者" prop="author" borderBottom>
                    <u--input v-model="curInputBook.author"></u--input>
                    <i style="color:#ff5a5f; font-size: 1.5rem; font-style:normal; margin-left:0.5rem">*</i>
                </u-form-item>
                <u-form-item labelWidth="auto" class="formItem" label="出版社" prop="publisher" borderBottom>
                    <u--input v-model="curInputBook.publisher"></u--input>
                    <i style="color:#ff5a5f; font-size: 1.5rem; font-style:normal; margin-left:0.5rem">*</i>
                </u-form-item>
                <u-form-item labelWidth="auto" class="formItem" label="出版日期" prop="publisherTime" borderBottom>
                    <u--input v-model="curInputBook.publisherTime"></u--input>
                </u-form-item>
                <u-form-item class="formItem" label="原价" prop="price" borderBottom>
                    <u--input v-model="curInputBook.price"></u--input>
                    <i style="color:#ff5a5f; font-size: 1.5rem; font-style:normal; margin-left:0.5rem">*</i>
                </u-form-item>
                <u-form-item class="formItem" label="现价" prop="curprice" borderBottom>
                    <u--input type="digit" v-model="curInputBook.curprice"></u--input>
                    <i style="color:#ff5a5f; font-size: 1.5rem; font-style:normal; margin-left:0.5rem">*</i>
                </u-form-item>
                <u-form-item class="formItem postage" label="邮费" prop="postage" borderBottom>
                    <u--input type="digit" :disabled="disabledProp" v-model="curInputBook.postage"></u--input>
                    <u-checkbox-group class="checkbox" @change="checkboxChange">
                        <u-checkbox :customStyle="{ marginBottom: '8px' }" label="包邮" name="postage">
                        </u-checkbox>
                    </u-checkbox-group>
                    <i style="color:#ff5a5f; font-size: 1.5rem; font-style:normal; margin-left:0.5rem">*</i>
                </u-form-item>
                <u-form-item labelWidth="auto" class="formItem" label="书籍简介" prop="summary" borderBottom>
                    <u--textarea height="100" v-model="curInputBook.summary"></u--textarea>
                </u-form-item>
                <u-form-item class="formItem" label="描述" prop="describe" borderBottom>
                    <u--textarea height="100" v-model="curInputBook.describe" placeholder="介绍一下你的书吧~"></u--textarea>
                    <i style="color:#ff5a5f; font-size: 1.5rem; font-style:normal; margin-left:0.5rem">*</i>
                </u-form-item>
                <u-form-item class="formItem" prop="classify" label="分类" borderBottom>
                    <view @click="showPicker = true">
                        <u--input disabled placeholder="请选择书籍分类" v-model="curInputBook.classify">
                        </u--input>
                    </view>
                    <u-picker :show="showPicker" ref="uPicker" :columns="columns" @confirm="confirmPicker"
                        closeOnClickOverlay @cancel="showPicker = false" @change="changePickerHandler"></u-picker>
                    <i style="color:#ff5a5f; font-size: 1.5rem; font-style:normal; margin-left:0.5rem">*</i>

                </u-form-item>
                <u-form-item class="formItem" label="图片" borderBottom>
                    <u-upload uploadText="上传图片" :fileList="curInputBook.imageList" :maxCount="5"
                        @afterRead="afterReadImageList" @delete="deleteImageList" multiple width="6rem" height="8rem">
                    </u-upload>
                </u-form-item>
            </u--form>
            <u-button class="btn" @click="release">{{ buttonText }}</u-button>
        </view>
    </view>
</template>

<script>

export default {
    mounted() {
        Object.assign(this.curInputBook, this.$store.state.sale.curInputBook)
        if (typeof this.curInputBook.coverImage == 'string') {

            this.buttonText = '确认修改'
            this.titleText = '更新信息'
        }
        let arrCover = []
        arrCover.push(this.curInputBook.coverImage)
        this.curInputBook.coverImage = []
        this.curInputBook.coverImage.push({
            url: this.curInputBook.image || arrCover[0],
            thumb: this.curInputBook.image || arrCover[0],
            type: "image",
            status: 'success',
            message: '',
        })
        let newArray = []

        if (typeof this.curInputBook.imageList == 'string') {
            newArray.push({
                url: this.curInputBook.imageList,
                thumb: this.curInputBook.imageList,
                type: 'image',
                message: ''
            })
        } else
            this.curInputBook.imageList.forEach(item => {
                let imgItem = {}
                imgItem.url = item
                imgItem.thumb = item
                imgItem.type = "image",
                    imgItem.status = 'success',
                    imgItem.message = '',
                    newArray.push(imgItem)
            })
        this.curInputBook.imageList = newArray
        this.initColumn()
    },
    data() {
        return {
            buttonText: '发布书籍',
            titleText: '录入信息',
            showPicker: false,
            columns: [],
            curInputBook: {
                author: '',//作者
                bookTitle: '',//书名
                ISBN: '',//ISBN
                publisher: '',//出版社
                publisherTime: '',//出版日期
                price: '',//原价
                curprice: '',//现价7
                postage: '',//邮费
                summary: '',//书籍简介
                describe: '',//描述
                imageList: [],//图片
                coverImage: [],//封面
                score: '',//评分
                alt: '',//alt
                classify: ''
            },
            rules: {
                bookTitle: {
                    type: 'string',
                    required: true,
                    message: '请输入书名',
                    trigger: ['blur', 'change']
                },
                author: {
                    type: 'string',
                    required: true,
                    message: '请输入作者',
                    trigger: ['blur', 'change']
                },
                price: {
                    type: 'string',
                    required: true,
                    message: '请输入原价',
                    trigger: ['blur', 'change']
                },
                curprice: {
                    required: true,
                    message: '请输入售卖价格',
                    trigger: ['blur', 'change']
                },
                postage: {
                    type: 'string',
                    required: true,
                    message: '请输入邮费',
                    trigger: ['blur', 'change']
                },
                describe: {
                    type: 'string',
                    required: true,
                    message: '请输入描述',
                    trigger: ['blur', 'change']
                },
                classify: {
                    required: true,
                    message: "请选择分类",
                    trigger: ['change']
                }
            },
            disabledProp: false,
        }
    },
    computed: {
        classifyList() {
            return this.$store.state.classify.classifyList || []
        },
        childrenList() {
            let data = this.classifyList
            let list = []
            data.forEach(item => {
                let childItem = []
                item.children.forEach(child => {
                    childItem.push(child.name)
                })
                list.push(childItem)
            })
            return list
        },
    },
    methods: {
        initColumn() {
            let data = this.classifyList
            let firstColumn = []
            let secondColumn = []
            data.forEach(item => {
                firstColumn.push(item.name)
            })
            //第一个为第二行
            data[0].children.forEach(item => {
                secondColumn.push(item.name)
            });
            this.columns = [firstColumn, secondColumn]
        },
        //修改书籍信息
        updateBookInfo() {

        },
        changePickerHandler(value) {
            const { columnIndex, index, picker = this.$refs.uPicker } = value
            if (columnIndex == 0) {
                picker.setColumnValues(1, this.childrenList[index])
            }
        },
        confirmPicker(chooseValue) {
            // 将选择的一级分类和二级分类使用/链接起来
            this.curInputBook.classify = chooseValue.value[0] + '/' + chooseValue.value[1]
            this.showPicker = false
        },
        release() {
            this.$refs.bookInfo.validate().then(res => {
                //处理bookInfo中的数据
                let list = []
                this.curInputBook.imageList.forEach(image => {
                    list.push(image.url)
                })
                let data = { ...this.curInputBook, coverImage: this.curInputBook.coverImage[0].url, imageList: list.join('&||&'), userImg: this.$store.state.user.userInfo.avatar, userName: this.$store.state.user.userInfo.nickName }
                delete data.image
                console.log(data)
                if (this.buttonText == '发布书籍') {
                    this.$store.dispatch('publishedBooks', data).then(res => {
                        if (res == 'success') {
                            this.$tools.toast('发布成功')
                            this.$Router.back()
                        } else {
                            this.$tools.toast('发布失败, 请稍后再试')
                        }
                    })
                } else {
                    delete data.isCollection
                    this.$store.dispatch('updateBookInfo', data).then(res => {
                        if (res == 'success') {
                            this.$tools.toast('修改成功')
                            this.$Router.back()
                        } else {
                            this.$tools.toast('修改失败, 请稍后再试')
                        }
                    })
                }

            })
        },
        checkboxChange(e) {
            // console.log(e)
            if (e[0] == "postage") {
                this.curInputBook.postage = '0'
                this.disabledProp = true
            }
            else {
                this.curInputBook.postage = ''
                this.disabledProp = false
            }
        },
        async afterReadImageList(event) {
            let lists = [].concat(event.file)
            let fileListLength = this.curInputBook.imageList.length
            lists.map(item => {
                this.curInputBook.imageList.push({
                    ...item,
                    status: 'uploading',
                    message: '上传中'
                })
            })
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadImageCover(lists[i].url)
                let item = this.curInputBook.imageList[fileListLength]
                this.curInputBook.imageList.splice(fileListLength, 1, Object.assign(item, {
                    type: "image",
                    thumb: result,
                    url: result,
                    status: 'success',
                    message: '',
                }))
                fileListLength++
            }
        },
        deleteImageList(event) {
            this.curInputBook.imageList.splice(event.index, 1)
        },
        async uploadImageCover(image) {
            try {
                return await this.$store.dispatch('uploadBookCover', image)
            } catch (e) {
                return 'error'
            }
        },
        async afterReadCoverImage(event) {
            let lists = event.file
            this.curInputBook.coverImage.push({
                ...lists,           //将文件的本机路径存放上去
                status: 'uploading',
                message: '上传中'
            })
            const result = await this.uploadImageCover(lists.url)
            this.curInputBook.coverImage.splice(0, 1, {
                type: "image",
                thumb: result,
                url: result,
                status: 'success',
                message: '',
            })
        },
        // async afterRead(event) {
        //     // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        //     let lists = [].concat(event.file)
        //     let fileListLen = this.coverImage.length
        //     lists.map((item) => {
        //         console.log(item)
        //         this.coverImage.push({
        //             ...item,
        //             status: 'uploading',
        //             message: '上传中'
        //         })
        //     })
        //     for (let i = 0; i < lists.length; i++) {
        //         const result = await this.uploadImageCover(lists[i].url)
        //         let item = this.coverImage[fileListLen]
        //         this.coverImage.splice(fileListLen, 1, Object.assign(item, {
        //             status: 'success',
        //             message: '',
        //             url: result
        //         }))
        //         fileListLen++
        //     }
        // },
        // async afterRead(event) {
        //     let image =event.file
        //     let imageLength=this.coverImage.length
        //     console.log(image)
        //     this.coverImage.push({
        //         status: "uploading",
        //         message: "上传中"
        //     })

        //     this.uploadImageCover(image.url).then(res => {
        //             console.log(res)
        //         if (res != 'error') {
        //             let item=this.coverImage[imageLength]
        //             this.coverImage.splice(imageLength, 1, Object.assign(item, {
        //                 status: "success",
        //                 message: '',
        //                 url: res
        //             }))
        //         }
        //     })

        // },
        deleteCoverImage(event) {
            //同时需删除服务器图片
            { }
            this.curInputBook.coverImage.splice(event.index, 1)
        },
    }
}
</script>

<style lang="scss" >
.main {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: white;
    padding-bottom: 2rem;

    .form {
        width: 95%;

        .formItem {}

        .postage {
            .checkbox {
                margin-left: 0.5rem;
            }
        }
    }

    .btn {
        width: 100%;
        margin-top: 1rem;
    }
}
</style>